package com.eight.cloud.springmvc.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.eight.cloud.core.global.model.JobUser;
import com.eight.cloud.core.global.model.LoginUser;
import com.eight.cloud.core.utils.format.ObjectFormat;
import com.eight.cloud.redisson.utils.TokenManager;
import com.eight.cloud.core.utils.supply.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.eight.cloud.core.global.constant.StrConstant.USER_INFO;

/**
 * 用户信息拦截器
 *
 * @ClassName: UserInfoInterceptor
 * @Author: TXC
 * @Date: 2024-10-08 22:44
 **/
public class UserInfoInterceptor implements HandlerInterceptor {
    private final TokenManager tokenManager;


    public UserInfoInterceptor(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = tokenManager.getAccessToken(request);
        if (StrUtil.isNotBlank(token)) {
            LoginUser userInfo = tokenManager.getLoginUser(token);
            if (ObjectUtil.isNotNull(userInfo)) {
                UserContext.setUser(userInfo);
            }
        } else {
            String userinfo = request.getHeader(USER_INFO);
            if (StrUtil.isNotBlank(userinfo)) {
                JobUser userInfo = ObjectFormat.strToObject(userinfo, JobUser.class);
                if (ObjectUtil.isNotNull(userInfo)) {
                    UserContext.setUser(userInfo);
                }
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        UserContext.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
